<template>
    <Row>
        <Col span="22" offset="1">
            <Form ref="CashFlow" :model="CashFlow" :rules="ruleValidate" :label-width="120" :style="{marginTop: '30px'}">
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="流水编码">
                            <Input v-model="CashFlow.NumCode" readonly placeholder="流水编码由系统自动生成" ></Input>
                        </FormItem>
                    </Col>
                </Row>
                
                <Divider orientation="left">流水银行信息</Divider>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="银行名称" prop="BankName">
                            <!-- <Input  v-model.trim="BankName" placeholder="例如：中国流水上海分行" >
                                <Button slot="append" @click="ShowDialog = true" icon="ios-search"></Button>
                            </Input> -->
                            <AutoComplete
                                v-model="BankName"
                                icon="ios-search"
                                placeholder="请输入银行名称！"
                                clearable
                                @on-search="SearchBank"
                                @on-select="SelectBank"
                                @on-clear="ClearBank"
                                style="width:100%">
                                <div class="auto-complete-item" v-for="item in Banks" :key="item.OrderNum">
                                    <div class="auto-complete-group">
                                        <span>{{ item.Company }}</span>
                                        <!-- <a href="https://www.baidu.com/search?q=iView" target="_blank">更多</a> -->
                                    </div>
                                    <Option v-for="option in item.Children" :value="option.Id" :key="option.Id">
                                        <span class="auto-complete-title">{{ option.Name }}</span>
                                        <span class="auto-complete-count">{{ option.Account.substr(option.Account.length-4,4) }} 账户尾号</span>
                                    </Option>
                                </div>
                                <!-- <a href="https://www.baidu.com/" target="_blank" class="auto-complete-more">查看所有结果</a> -->
                            </AutoComplete>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="银行账号" prop="BankAccount">
                            <Input v-model.trim="CashFlow.BankAccount" readonly placeholder="例如：620000xxxxxxxxxx7843"></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="账户尾号">
                            <Input v-model.trim="AccountTail" readonly placeholder="填写流水账户后自动计算取最后四位，例如：7843" ></Input>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="账户性质"  prop="AccountType">
                            <!-- <Input v-model.trim="AccountType" readonly placeholder="例如：直营账户、一般账户" ></Input> -->
                            <Select v-model.trim="AccountType" filterable disabled >
                                <Option v-for="item in AccountTypes" :value=item.value :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>

                <Divider orientation="left">流水项目信息</Divider>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="项目编码" prop="ProjectCode">
                            <!-- <Input v-model="CashFlow.ProjectCode" placeholder="请选择项目编码" >
                                <Button slot="append" @click="ShowDialog = true" icon="ios-search"></Button>
                            </Input> -->
                            <AutoComplete
                                v-model="CashFlow.ProjectCode"
                                icon="ios-search"
                                clearable
                                @on-search="SearchProject"
                                @on-select="SelectProject"
                                @on-clear="ClearProject"
                                placeholder="请输入项目名称！"
                                style="width:100%">
                                <div class="auto-complete-item" v-for="item in Projects" :key="item.OrderNum">
                                    <div class="auto-complete-group">
                                        <span>{{ item.Company }}</span>
                                        <a href="#">更多</a>
                                    </div>
                                    <Option v-for="option in item.Children" :value="option.Id" :key="option.Id">
                                        <span class="auto-complete-title"> {{ option.Name }} </span>
                                        <span class="auto-complete-count"> {{ option.NumCode }} 项目编码</span>
                                    </Option>
                                </div>
                               <!--  <a href="https://www.baidu.com/search?q=iView" target="_blank" class="auto-complete-more">查看所有结果</a> -->
                            </AutoComplete>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="项目名称" prop="ProjectName">
                            <Input  v-model.trim="CashFlow.ProjectName" readonly placeholder="例如：杭州之江云镜二标" ></Input>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="确认标记" prop="FundsStatus">
                            <Select v-model="CashFlow.FundsStatus" >
                                <Option v-for="item in FundsStatus" :value=item.value :key="item.label">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="分公司" prop="Company">
                            <!-- <Input v-model.trim="Company" readonly placeholder="例如：绍兴分公司、杭州分公司、宁波分公司" ></Input> -->
                            <Select v-model.trim="Company" filterable disabled >
                                <Option v-for="item in Companys" :value=item.value :key="item.Id">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="工程类型" prop="ItemType">
                            <!-- <Input v-model.trim="ItemType" readonly placeholder="例如：土建、消防、涂料、其他" ></Input> -->
                            <Select v-model.trim="ItemType" filterable disabled >
                                <Option v-for="item in ProjectTypes" :value=item.value :key="item.Id">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="20" offset="2">
                        <FormItem label="项目地块" prop="LandParcel">
                            <Input v-model.trim="LandParcel" readonly placeholder="例如：3#地块" ></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Divider orientation="left">供货单位信息</Divider>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="供货单位" prop="SupplierFactory">
                            <Input v-model.trim="CashFlow.SupplierFactory" placeholder="例如：宿州市隆腾建筑工程有限公司" ></Input>
                        </FormItem>
                    </Col>
                    <Col span="10">
                        <FormItem label="银行账户" prop="SupplierBankAccount">
                            <Input v-model.trim="CashFlow.SupplierBankAccount" placeholder="6200000xxxxxx52152" ></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Divider orientation="left">流水调拨信息</Divider>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="金额（小写）" prop="Amount">
                            <Input v-model.number="CashFlow.Amount" placeholder="实际发生的金额" >
                                <span slot="suffix"><i>元</i ></span>
                                <Icon type="logo-yen" slot="prefix" />
                            </Input>
                        </FormItem>
                    </Col>
                    <Col span="10">
                        <FormItem label="金额（大写）" prop="BigAmount">
                            <Input v-model.trim="BigMoney" readonly placeholder="实际发生的金额" ></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="10" offset="2">
                        <FormItem label="金额方向" prop="MoneyForward">
                            <Select v-model.trim="CashFlow.MoneyForward" >
                                <Option v-for="item in MoneyForwards" :value=item.value :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="款项类型" prop="FundsType">
                            <Select v-model.trim="CashFlow.FundsType" filterable allow-create @on-create="handleCreateFundsType" >
                                <Option v-for="item in FundsTypes" :value=item.value :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="10" offset="2">
                        <FormItem label="付款时间" prop="AllocationTime">
                            <DatePicker v-model.trim="AllocationTime" @on-change="PaytimeHandle" format="yyyyMMdd"  type="date" placeholder="请选择时间！" style="width: 100%"></DatePicker>
                        </FormItem>
                    </Col>
                    <Col span="10" >
                        <FormItem label="付款操作人" prop="PayOperator">
                            <Input v-model.trim="PayOperator" disabled placeholder="例如：赵烨" ></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="20" offset="2">
                        <FormItem label="资金摘要" prop="Summary">
                            <Input v-model="CashFlow.Summary" maxlength="250" type="textarea" :autosize="{minRows: 5,maxRows: 5}" show-word-limit placeholder="请输入资金流摘要！"></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="20" offset="2" style="text-align:center;margin-top:58px">
                        <Button type="primary" @click="Submit('CashFlow')">提交</Button>
                        <Button @click="Reset('CashFlow')" style="margin-left: 108px">重置</Button>
                    </Col>
                </Row>
            </Form>
        </Col>
    </Row>
</template>
<script>
import { mapState } from "vuex";
import 
{ 
    CreateCode,
    GetOne,
    Create,
    Update,
    QueryBankInfo,
    QueryProjectInfo,
    QueryBankById,
    QueryProjectById,
    QueryAdministrativeByCode,
    LoadBankType,
    LoadProjectType,
    LoadFundsType,
    LoadCompany
} from '@/axios/api/CashFlowAPI'
import { BigMoney } from '@/axios/api/BankAPI'
import { GetOne as GetUser } from '@/axios/api/UsersAPI'
import { formatTimeToStr } from '@/userdefine/date.js';
import { getUserInfo } from '@/store/localStorage/cookies';
import { Create as CreateFundsType } from '@/axios/api/FundsTypeAPI'

export default {
    computed:{
        ...mapState('cashflow',[
            'currentCashFlowID',
            'pageIndex',
            'pageSize',
        ])
    },
    components: {
        
    },
    mounted: function(){
        
        //console.log(this.currentCashFlowID)
        if(this.currentCashFlowID != ''){
            this.$Spin.show();
        }
        setTimeout(() => {
            this.$Spin.hide();
        }, 1000);

        //获取银行类型
        LoadBankType().then(res => {
            const list = res.map(item => {
                return {
                    value: item.Code.toString(),
                    label: item.Name
                };
            });
            this.AccountTypes = list;
        })

        //获取工程项目类型
        LoadProjectType().then(res => {
            const list = res.map(item => {
                return {
                    value: item.Code.toString(),
                    label: item.Name
                };
            });
            this.ProjectTypes = list;
        })

        //获取款项类型
        LoadFundsType().then(res => {
            const list = res.map(item => {
                return {
                    value: item.Code.toString(),
                    label: item.Name
                };
            });
            this.FundsTypes = list;
        })

        //获取公司列表
        LoadCompany().then(res => {
            const list = res.map(item => {
                return {
                    value: item.Id.toString(),
                    label: item.Name,
                    Id: item.Id.toString()
                };
            });
            this.Companys = list;
        })
        
        if(this.currentCashFlowID != ''){
            GetOne(this.currentCashFlowID).then(res => {
                this.CashFlow.Id = res.Id;
                this.CashFlow.Num = res.Num;
                this.CashFlow.NumCode = res.NumCode;
                this.CashFlow.BankGuid = res.BankGuid;
                this.CashFlow.ProjectGuid = res.ProjectGuid;
                this.CashFlow.Confirm = res.Confirm;
                this.CashFlow.SupplierFactory = res.SupplierFactory;
                this.CashFlow.SupplierBankAccount = res.SupplierBankAccount;
                this.CashFlow.Summary = res.Summary;
                this.CashFlow.MoneyForward = res.MoneyForward;
                this.CashFlow.FundsType = res.FundsType;
                this.CashFlow.IsConfirm = res.IsConfirm;
                this.CashFlow.Amount = res.Amount;
                this.CashFlow.AllocationTime = res.AllocationTime ;
                this.AllocationTime = new Date(res.AllocationTime.toString().substr(0,4) + "-"+ res.AllocationTime.toString().substr(4,2)+ "-"+ res.AllocationTime.toString().substr(6,2));
                this.FreezeMoney = res.FreezeMoney;
                this.CashFlow.PayOperatorId = res.PayOperatorId;
                this.CashFlow.CreateTime = res.CreateTime;
            });
        }
        else{
            CreateCode().then(res => {
                this.CashFlow.NumCode = res.toString();
            })

            this.CashFlow.AllocationTime = Number.parseInt(formatTimeToStr(new Date(),"yyyyMMdd"))
        }

        if(this.CashFlow.Id == '00000000-0000-0000-0000-000000000000'){
            
            var currentUserInfo = JSON.parse(getUserInfo());
            this.PayOperator = currentUserInfo.Name;
            this.CashFlow.PayOperatorId = currentUserInfo.Id;
        }
        else{
            GetUser(this.CashFlow.PayOperatorId).then(res => {
                this.PayOperator = res.Name;
            })
        }
    },
    data () {
        return {
            CashFlow: {
                Id: '00000000-0000-0000-0000-000000000000',
                Num: 1,
                NumCode: '',
                BankGuid: '00000000-0000-0000-0000-000000000000',
                ProjectGuid: '00000000-0000-0000-0000-000000000000',
                FundsStatus: 1,
                SupplierFactory: '',
                SupplierBankAccount: '',
                Summary: '',
                MoneyForward: '',
                FundsType: '',
                Amount: 0.0,
                AllocationTime: 0,
                FreezeMoney: '00000000-0000-0000-0000-000000000000',
                PayOperatorId: '00000000-0000-0000-0000-000000000000',
                CreateTime: new Date()
            },
            ruleValidate: {
                //Num: [{ type: 'number', message: '只能输入数字', trigger: 'blur' }],
                //BankName: [{ required: true, message: '银行名称为必填项！', trigger: 'blur'  }],
                Amount: [{ type: 'number', message: '只能输入数字', trigger: 'blur' }],
                //SupplierFactory: [{ required: true, message: '供货单位为必填项！', trigger: 'blur'  }]
                MoneyForward: [{ required: true, message: '金额方向为必填项！', trigger: 'blur'  }],
                FundsType: [{ required: true, message: '款项类别为必选！', trigger: 'blur'  }]
            },
            MoneyForwards:[
                {
                    value: '0',
                    label: "收入"
                },
                {
                    value: '1',
                    label: "支出"
                }
            ],
            FundsStatus: [
                {
                    value: '0',
                    label: "待确认"
                },
                {
                    value: '1',
                    label: "已确认"
                }
            ],
            FundsTypes:[],
            ProjectTypes: [],
            AccountTypes: [],
            Companys:[],
            Banks: [],
            Projects: [],
            ShowDialog: false,
            callmodal: "CashFlow-Sheet",
            Province:[],
            City:[],
            Zone:[],
            ProvinceStatus: false,
            CityStatus: false,
            ZoneStatus: false,
            BankName: '',
            AccountTail: '',
            AccountType: '',
            PayOperator: '',
            ProjectProvince: '',
            ProjectCity: '',
            ProjectZone: '',
            Company: '',
            ItemType: '',
            LandParcel: '',
            DetailAddress:'',
            AllocationTime:  new Date(),
            Address: '',
            BigMoney:''
        }
    },
    watch: {
        'CashFlow.Account'(value){
            if(value != '' && value != null){
                this.AccountTail = value.substr(value.length-4,4);
            }
        },
        'CashFlow.Amount'(value){
            if(value != '' && value != null){
                BigMoney(value).then(res => {
                    this.BigMoney = res;
                })
            }
        },
        'CashFlow.BankGuid'(value){
            QueryBankById(value).then(res => {
                if(res){
                    this.CashFlow.BankGuid = res.Id;
                    this.CashFlow.BankAccount = res.Account;
                    this.BankName = res.Name;
                    this.AccountTail = res.Account.substr(res.Account.length-4,4);
                    this.AccountType = res.AccountType;
                }
            })
        },
        'CashFlow.ProjectGuid'(value){
            QueryProjectById(value).then(projectres => {
                this.CashFlow.ProjectGuid = projectres.Id;
                this.CashFlow.ProjectCode = projectres.NumCode;
                this.CashFlow.ProjectName = projectres.Name;

                //开始查询省份
                QueryAdministrativeByCode(projectres.Province).then(provinceres => {
                    const one =  {
                        value: provinceres.Code.toString(),
                        label: provinceres.Name,
                        Id: provinceres.Id
                    };

                    if(this.Province.indexOf(item => item.Id = one.Id) === -1){
                        this.Province.push(one);
                    }

                    //开始查询城市
                    QueryAdministrativeByCode(projectres.City).then(cityres => {
                        if(cityres){
                            //console.log(cityres);
                            const one =  {
                                value: cityres.Code.toString(),
                                label: cityres.Name,
                                Id: cityres.Id
                            };

                            if(this.City.indexOf(item => item.Id = one.Id) === -1){
                                this.City.push(one);
                            }
                            
                        }

                        //开始查询地区
                        QueryAdministrativeByCode(projectres.Zone).then(zoneres => {
                            if(zoneres){
                                //console.log(zoneres)
                                const one =  {
                                    value: zoneres.Code.toString(),
                                    label: zoneres.Name,
                                    Id: zoneres.Id
                                };

                                if(this.Zone.indexOf(item => item.Id = one.Id) === -1){
                                    this.Zone.push(one);
                                }
                            }
                        })
                        //结束查询地区
                    })
                    //结束查询城市
                })
                //结束查询省份
                
                this.ProjectProvince = projectres.Province;
                this.ProjectCity = projectres.City;
                this.ProjectZone = projectres.Zone;
                this.Company = projectres.Company;
                this.ItemType = projectres.ItemType;
                this.LandParcel = projectres.LandParcel;
                this.DetailAddress = projectres.DetailAddress;
            })
        }
    },
    methods: {
        Submit (name){
            //this.$Message.success('按了OK键');
             this.$refs[name].validate((valid) => {
                if (valid) {
                    if(this.CashFlow.Id == '00000000-0000-0000-0000-000000000000'){
                        this.$Message.success('校验通过!');
                        Create(this.CashFlow).then(res => {
                            if(res > 0){

                                setTimeout(() => {
                                    this.$store.dispatch('cashflow/UpdateTableAsync',{
                                        PageIndex: this.pageIndex,
                                        PageSize: this.pageSize
                                    });

                                     this.$Notice.success({
                                        title: '操作提示',
                                        desc: '保存成功！ '
                                    });
                                }, 1000)
                               
                            }
                            else{
                                this.$Notice.error({
                                    title: '操作提示',
                                    desc: '保存失败！ '
                                });
                            }
                        }).catch(err =>{
                            this.$Notice.error({
                                title: '操作提示',
                                desc: '保存失败：' + err.data + '!'
                            });
                        })
                        
                    }
                    else{
                        this.$Message.success('校验通过!');
                        
                        Update(this.CashFlow).then(res => {
                            if(res > 0){
                                setTimeout(() => {
                                    this.$store.dispatch('cashflow/UpdateTableAsync',{
                                        PageIndex: this.pageIndex,
                                        PageSize: this.pageSize
                                    });

                                     this.$Notice.success({
                                        title: '操作提示',
                                        desc: '更新成功！'
                                    });
                                }, 1000)
                            }
                            else{
                                this.$Notice.success({
                                    title: '操作提示',
                                    desc: '更新失败！'
                                });
                            }
                        }).catch(err =>{
                            this.$Notice.error({
                                title: '操作提示',
                                desc: '更新失败：' + err.data + '!'
                            });
                        })
                    }
                    this.ChangeModal();
                } else {
                    this.$Message.error('校验失败!');
                    //this.ChangeModal('CashFlow');
                }
            })
            
        },
        Reset (name){
            this.$refs[name].resetFields();
        },
        ChangeModal (){
            //this.$refs[name].resetFields();
            console.log(this.cashflowId)
            this.$store.commit('cashflow/CHANGE_MODAL');
            this.$router.push('/funds/CashFlow')
        },
        handleCreateFundsType (val) {

            CreateCode().then(res => {

                var FundsType = {
                    Code: res.toString(),
                    Name: val,
                    Id: '00000000-0000-0000-0000-000000000000'
                };
                
                CreateFundsType(FundsType).then(res => {
                    if(res > 0){
                        this.AccountTypes.push({
                            value: FundsType.Code,
                            label: FundsType.Name,
                            Id: FundsType.Id
                        });
                        this.FundsType = FundsType.Code;
                    }
                })
            })

            
        },
        PaytimeHandle (value){
            //console.log('>>>>>>>>>>>>>>>time',value)
            this.CashFlow.AllocationTime = Number.parseInt(value);
            //console.log('>>>>>>>>>>>>>>>CashFlow.AllocationTime',value);
        },
        SearchBank(value){
            QueryBankInfo(value).then(res => {
                this.Banks = res;
            })
        },
        SelectBank(value){
            if(value){
                this.CashFlow.BankGuid = value;
            }
        },
        SearchProject(value){
            QueryProjectInfo(value).then(res => {
                //console.log('>>>>>>>>>>>>>SearchProject',res);
                this.Projects = res;
            })
        },
        SelectProject(value){
            this.CashFlow.ProjectGuid = value;
        },
        ClearBank(){
            this.CashFlow.BankGuid = '00000000-0000-0000-0000-000000000000'
            this.CashFlow.BankAccount = '';
            this.AccountTail = '';
            this.AccountType = '';
            this.Banks = [];
        },
        ClearProject(){
            this.CashFlow.ProjectGuid = '00000000-0000-0000-0000-000000000000'
            this.CashFlow.ProjectName = '';
            this.Company = '';
            this.LandParcel = '';
            this.ItemType = '';
            this.Projects = [];
        }
    }
}
</script>
<style>
    .auto-complete-item{
        padding: 4px 0;
        border-bottom: 1px solid #F6F6F6;
    }
    .auto-complete-group{
        font-size: 12px;
        padding: 4px 6px;
        margin-bottom:7px;
    }
    .auto-complete-group span{
        color: #666;
        font-weight: bold;
    }
    .auto-complete-group a{
        float: right;
    }
    .auto-complete-count{
        float: right;
        color: #999;
    }
    .auto-complete-more{
        display: block;
        margin: 0 auto;
        padding: 4px;
        text-align: center;
        font-size: 12px;
    }
</style>